package 栈和队列.删除相邻重复项;

import java.util.Deque;
import java.util.Stack;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/1/29 13:50
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        String s = "abbaca";
        System.out.println(removeDuplicates(s));
    }


    //利用栈的原理
    public static String removeDuplicates(String s) {
        Stack<Character> stack = new Stack<>();
        for (char c:s.toCharArray()){
            if (!stack.empty() && stack.peek() == c){
                stack.pop();
            }else {
                stack.push(c);
            }
        }
        String result = "";
        while (!stack.empty()){
            result = stack.pop() + result;
        }
        return result;
    }

    //官方解法
    public static String removeDuplicates2(String s) {
        StringBuffer stack = new StringBuffer();
        int top = -1;
        for (int i = 0; i < s.length(); ++i) {
            char ch = s.charAt(i);
            if (top >= 0 && stack.charAt(top) == ch) {
                stack.deleteCharAt(top);
                --top;
            } else {
                stack.append(ch);
                ++top;
            }
        }
        return stack.toString();
    }

}
